from dash import Input, Output, State, callback_context, html, dcc, ALL # 引入 ALL
from models import db, RepairRecord, Organization, Department, Product # 确保导入所需模型
import dash_bootstrap_components as dbc # 引入 dbc
import dash


# 新增报修Modal组件
def create_new_repair_modal():
    """创建新增报修的Modal组件"""
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("新增报修"), close_button=True),
            dbc.ModalBody([
                dbc.Form([
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("所属机构", html_for="new-repair-org"),
                            dcc.Dropdown(
                                id="new-repair-org",
                                options=[], # 动态加载
                                placeholder="请选择机构",
                                className="mb-3"
                            ),
                        ], width=6),
                        dbc.Col([
                            dbc.Label("所属科室", html_for="new-repair-dept"),
                            dcc.Dropdown(
                                id="new-repair-dept",
                                options=[], # 动态加载
                                placeholder="请先选择机构",
                                className="mb-3",
                                disabled=True # 初始禁用
                            ),
                        ], width=6),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("设备名称", html_for="new-repair-device"),
                            dcc.Dropdown(
                                id="new-repair-device",
                                options=[], # 动态加载
                                placeholder="请先选择科室",
                                className="mb-3",
                                disabled=True # 初始禁用
                            ),
                        ], width=12),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("故障现象", html_for="new-repair-fault"),
                            dbc.Textarea(
                                id="new-repair-fault",
                                placeholder="请描述故障现象",
                                style={"height": "100px"},
                                className="mb-3"
                            ),
                        ], width=12),
                    ]),
                    dbc.Row([
                         dbc.Col([
                            dbc.Label("叫修人姓名", html_for="new-repair-caller"),
                            dbc.Input(
                                type="text",
                                id="new-repair-caller",
                                placeholder="请输入叫修人姓名",
                                className="mb-3"
                            ),
                        ], width=6),
                    ]),
                    dbc.Alert(id="new-repair-alert", color="danger", is_open=False, duration=4000),
                ]),
            ]),
            dbc.ModalFooter([
                dbc.Button("放弃", id="new-repair-cancel", className="me-2", color="secondary"),
                dbc.Button("提交", id="new-repair-confirm", color="primary"),
            ]),
        ],
        id="new-repair-modal",
        is_open=False,
        size="lg", # 可以调整大小: sm, lg, xl
        backdrop="static", # 点击背景不关闭
        centered=True, # <--- 添加此行以居中显示
        scrollable=True,
        style={"marginTop": "120px"} 
        # className="new-repair-modal-instance",
        # style={"opacity": "1 !important"}
    )

# 注册Modal相关的回调函数
def register_modal_callbacks(dash_app):
    """注册与Modal相关的回调函数"""
    from dash import Input, Output
    from models import Department

    def register_filter_callbacks(app):
        @app.callback(
            Output("filter-dept", "options"),
            Output("filter-dept", "value"),
            Input("filter-org", "value"),
        )
        def update_dept_options(selected_org):
            if selected_org:
                # 查询该机构下的所有科室
                depts = Department.query.filter_by(org_name=selected_org, is_active=True).all()
                options = [{"label": d.dept_name, "value": d.dept_name} for d in depts]
                # 默认不选中任何科室
                return options, None
            # 没选机构时，科室下拉为空
            return [], None

    # --- 新增：控制新增报修Modal的显示与隐藏 ---
    @dash_app.callback(
        Output("new-repair-modal", "is_open"),
        Output("new-repair-alert", "is_open", allow_duplicate=True), # 清空提示
        Output("new-repair-alert", "children", allow_duplicate=True), # 清空提示内容
        # 清空表单字段
        Output("new-repair-org", "value", allow_duplicate=True),
        Output("new-repair-dept", "value", allow_duplicate=True),
        Output("new-repair-device", "value", allow_duplicate=True),
        Output("new-repair-fault", "value", allow_duplicate=True),
        Output("new-repair-caller", "value", allow_duplicate=True),
        Output("new-repair-dept", "disabled", allow_duplicate=True),
        Output("new-repair-device", "disabled", allow_duplicate=True),
        [Input("new-repair-btn", "n_clicks"),
         Input("new-repair-cancel", "n_clicks"),
         Input("new-repair-confirm", "n_clicks")], # 监听确认按钮
        [State("new-repair-modal", "is_open")],
        prevent_initial_call=True
    )
    def toggle_new_repair_modal(n_open, n_cancel, n_confirm, is_open):
        ctx = dash.callback_context
        triggered_id = ctx.triggered_id
        print(f"--- toggle_new_repair_modal triggered by: {triggered_id} ---") # 添加打印语句

        if not triggered_id:
             print("No trigger ID found.")
             return is_open, False, "", None, None, None, "", "", True, True

        if triggered_id == "new-repair-btn":
            print("Opening new-repair-modal.")
            # 打开时清空表单并重置状态
            return True, False, "", None, None, None, "", "", True, True
        elif triggered_id == "new-repair-cancel":
            print("Closing new-repair-modal via Cancel.")
            # 取消时关闭
            return False, False, "", None, None, None, "", "", True, True
        elif triggered_id == "new-repair-confirm":
            print("Confirm button clicked, modal close handled by submit callback.")
            # 确认按钮由 submit_new_repair 回调处理关闭逻辑，这里不处理
            return dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update

        print("No relevant trigger, returning current state.")
        return is_open, False, "", dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update


def create_repair_respond_modal():
    """创建维修响应的Modal组件"""
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("维修响应"), close_button=True),
            dbc.ModalBody([
                # 维修信息展示区
                html.Div(id="repair-respond-info", style={"marginBottom": "16px"}),
                dbc.Form([
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修人员", html_for="repair-respond-person"),
                            dbc.Input(
                                type="text",
                                id="repair-respond-person",
                                placeholder="请输入维修人员",
                                className="mb-3"
                            ),
                        ], width=6),
                        dbc.Col([
                            dbc.Label("维修公司", html_for="repair-respond-company"),
                            dbc.Input(
                                type="text",
                                id="repair-respond-company",
                                placeholder="请输入维修公司",
                                className="mb-3"
                            ),
                        ], width=6),
                        dbc.Col([
                            dbc.Label("维修类型", html_for="repair-respond-company"),
                            dbc.Input(
                                type="text",
                                id="repair-respond-repairtype",
                                placeholder="请输入维修类型",
                                className="mb-3"
                            ),
                        ], width=6),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("预计完成日期", html_for="repair-respond-expected-date"),
                            dcc.DatePickerSingle(
                                id="repair-respond-expected-date",
                                placeholder="请选择预计完成日期",
                                className="mb-3",
                                display_format="YYYY-MM-DD"
                            ),
                        ], width=6),
                        dbc.Col([
                            dbc.Label("备注", html_for="repair-respond-remarks"),
                            dbc.Textarea(
                                id="repair-respond-remarks",
                                placeholder="请输入备注",
                                className="mb-3"
                            ),
                        ], width=6),
                    ]),
                    dbc.Alert(id="repair-respond-alert", color="danger", is_open=False, duration=4000),
                ]),
            ]),
            dbc.ModalFooter([
                dbc.Button("放弃", id="repair-respond-cancel", className="me-2", color="secondary"),
                dbc.Button("提交", id="repair-respond-confirm", color="primary"),
            ]),
        ],
        id="repair-respond-modal",
        is_open=False,
        size="lg",
        backdrop="static",
        centered=True,
        scrollable=True,
        style={"marginTop": "120px"}
    )


def create_repair_complete_modal():
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("维修完成"), close_button=True),
            dbc.ModalBody([
                # 维修信息展示区
                html.Div(id="repair-complete-info", style={"marginBottom": "16px"}),
                dbc.Form([
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修内容", html_for="repair-complete-content"),
                            dbc.Textarea(
                                id="repair-complete-content",
                                placeholder="请输入维修内容",
                                className="mb-3"
                            ),
                        ], width=12),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修结果", html_for="repair-complete-result"),
                            dbc.Input(
                                type="text",
                                id="repair-complete-result",
                                placeholder="请输入维修结果",
                                className="mb-3"
                            ),
                        ], width=6),
                        dbc.Col([
                            dbc.Label("维修费用", html_for="repair-complete-cost"),
                            dbc.Input(
                                type="number",
                                id="repair-complete-cost",
                                placeholder="请输入维修费用",
                                className="mb-3"
                            ),
                        ], width=6),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("更换配件", html_for="repair-complete-parts"),
                            dbc.Textarea(
                                id="repair-complete-parts",
                                placeholder="请输入更换配件",
                                className="mb-3"
                            ),
                        ], width=12),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("备注", html_for="repair-complete-remarks"),
                            dbc.Textarea(
                                id="repair-complete-remarks",
                                placeholder="请输入备注",
                                className="mb-3"
                            ),
                        ], width=12),
                    ]),
                    dbc.Alert(id="repair-complete-alert", color="danger", is_open=False, duration=4000),
                ]),
            ]),
            dbc.ModalFooter([
                dbc.Button("放弃", id="repair-complete-cancel", className="me-2", color="secondary"),
                dbc.Button("提交", id="repair-complete-confirm", color="primary"),
            ]),
        ],
        id="repair-complete-modal",
        is_open=False,
        size="lg",
        backdrop="static",
        centered=True,
        scrollable=True,
        style={"marginTop": "120px"}
    )


def create_upload_proof_modal():
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("上传工单图片"), close_button=True),
            dbc.ModalBody(
                html.Div([
                    # 横向flex布局容器
                    html.Div([
                        # 左侧上传区
                        html.Div([
                            dcc.Upload(
                                id="upload-proof",
                                children=html.Div([
                                    "拖拽或点击选择图片上传"
                                ]),
                                style={
                                    "width": "100%", "height": "100px", "lineHeight": "100px",
                                    "borderWidth": "1px", "borderStyle": "dashed",
                                    "borderRadius": "5px", "textAlign": "center", "margin": "100px 0"
                                },
                                multiple=False
                            ),
                            # dbc.Alert(id="upload-proof-alert", color="info", is_open=False, duration=4000),
                            dbc.Alert(id="upload-proof-alert", color="info", is_open=False, style={"height": "40px"}),
                        ], style={"width": "30%", "minWidth": "200px", "paddingRight": "16px", "marginTop": "32px","flex": "1",
                                }), 
                        # 右侧预览区
                        html.Div(
                            id="proof-preview-area",
                            style={"width": "70%", "minWidth": "250px", "display": "flex", "alignItems": "center"}
                        ),
                        dcc.Store(id="proof-preview-refresh"), # 用于刷新预览
                    ], style={"display": "flex", "flexDirection": "row", "width": "100%"})
                ])
            ),
            dbc.ModalFooter([
                dbc.Button("关闭", id="upload-proof-cancel", color="secondary"),
            ]),
        ],
        id="upload-proof-modal",
        is_open=False,
        size="lg",
        centered=True,
        scrollable=True,
        style={"marginTop": "120px"} 
    )